package com.ita.tba.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.ita.tba.dao.DishDao;
import com.ita.tba.po.Dish;
import com.ita.tba.util.DbUtil;

public class DishDaoImpl implements DishDao{

	@Override
	public List<Dish> selectAllDishes() {
		List<Dish> dishList = new ArrayList<Dish>();
		String sql = "select * from tbadish order by dishid";

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		
		try {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()) {
				Dish dish = new Dish();
				dish.setDishId(rs.getInt("dishid"));
				dish.setDname(rs.getString("dname"));
				dish.setPrice(rs.getDouble("price"));
				dish.setImg(rs.getString("img"));
				dishList.add(dish);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, rs);
		}
		
		return dishList;
	}

	@Override
	public int selectDid(String dname) {
			String sql = "select dishid from tbadish where dname=?";
			
			int did = -1;
			Connection con = null;
			PreparedStatement pst = null;
			ResultSet rs = null;
			con = DbUtil.connect();
			
			try {
				pst = con.prepareStatement(sql);
				pst.setString(1, dname);
				rs = pst.executeQuery();
				while(rs.next()){
					did = rs.getInt("dishid");
				}

			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DbUtil.free(con, pst, rs);
			}
		return did;
	}

}
